import java.io.IOException;
import java.net.Socket;

// 将 客户端连接 抽象为 线程可执行实体
public class ClientHandler implements Runnable {
    public ClientHandler(Socket clientSocket, Router router) {
        this.clientSocket = clientSocket;
        this.router = router;
        System.out.printf("获取客户端连接：[%s]\n", clientSocket.getInetAddress().getHostName());
    }

    @Override
    public void run() {
        HttpRequest request = null;
        HttpResponse response = null;

        try {
            request = new HttpRequest(clientSocket);
            response = new HttpResponse(clientSocket);
            Router.RouteMatch routeMatch = router.findRoute(request.getMethod(), request.getPath());

            if (routeMatch != null) {
                // 设置路径参数
                routeMatch.getPathParameters().forEach(request::setPathParameter);

                // 执行处理器
                RequestHandler handler = routeMatch.getHandler();
                handler.handle(request, response);
            } else {
                response.sendError(404, "请求的路径不存在: " + request.getPath());
            }
        } catch (Exception e) {
            try {
                if (response != null) {
                    if (e instanceof IOException) {
                        response.sendError(400, "请求格式错误: " + e.getMessage());
                    } else {
                        response.sendError(500, "服务器内部错误: " + e.getMessage());
                    }
                }
            } catch (IOException ex) {
                System.err.println("发送错误响应时出错: " + ex.getMessage());
            }
            System.err.println("处理请求时出错: " + e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    private final Socket clientSocket;  // IO 套接字
    private final Router router;        // 业务路由器
}
